package com.atfusu.config;

import com.atfusu.bean.entity.Admin;
import com.atfusu.service.AdminService;
import com.atfusu.service.PermissionService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Title:
 * Author: fusu
 * DateTime:  2022/12/5
 * Description:
 **/
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @DubboReference
    private AdminService adminService;

    @DubboReference
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.getAdminByUsername(username);
        if (admin == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        //AuthorityUtils.commaSeparatedStringToAuthorityList("")用于分配权限
        //用户功能权限
        List<String> codes = permissionService.findPermissionCodeByAdminId(admin.getId());
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String code : codes) {
            if (StringUtils.isEmpty(code)) {
                continue;
            }
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(code);
            authorities.add(authority);
        }
        return new User(username, admin.getPassword(), authorities);
    }
}
